<?php

class AuthitemController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';
        public $layout='//layouts/column1';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','checkExistRole'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	
	private function insertMenuRelatedItems($rolename=null){
		if($rolename==null) return false;
		Authitemchild::model()->deleteRows($rolename);		
		if(isset($_POST['selectView'])){
			Authitemchild::model()->insertRows($rolename,$_POST['selectView'],'INDEX');
		}
		if(isset($_POST['selectCreate'])){
			Authitemchild::model()->insertRows($rolename,$_POST['selectCreate'],Authitem::OPERATION_TYPE_CREATE);
		}
		if(isset($_POST['selectUpdate'])){
			Authitemchild::model()->insertRows($rolename,$_POST['selectUpdate'],Authitem::OPERATION_TYPE_UPDATE);
		}
		if(isset($_POST['selectDelete'])){
			Authitemchild::model()->insertRows($rolename,$_POST['selectDelete'],Authitem::OPERATION_TYPE_DELETE);
		}
		if(isset($_POST['selectPosting'])){
			Authitemchild::model()->insertRows($rolename,$_POST['selectPosting'],Authitem::OPERATION_TYPE_POSTING);
		}
		Authitemchild::model()->insertRows($rolename,array(),Authitem::OPERATION_TYPE_OTHERS);
	}
	private function performSave($name=null){
        $transaction = Yii::app()->db->beginTransaction(); //memulai transaksi
        try {
        	$model = Authitem::model()->find('name=\''.$name.'\'');
        	if($name===null)
        		$model=new Authitem;        	
            $model->attributes=$_POST['Authitem'];
            $model->type=2;
            $model->description=$_POST['Authitem']['description'];
            $model->save();
            Authassignment::model()->deleteByItemname($model->name);
            if(isset($_POST['selectUser'])){
            	foreach($_POST['selectUser'] as $selectedUser){
					$authAssignmentModel = new Authassignment();
                    $authAssignmentModel->userid = $selectedUser;
                    $authAssignmentModel->itemname = $model->name;
                    $authAssignmentModel->save();
				}
            }
            $this->insertMenuRelatedItems($model->name);
            $transaction->commit();
        	return true;        
        } catch (Exception $exc) {
            $transaction->rollback();
            throw  new CHttpException(400, $exc->getMessage());
        }
        
	}
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$this->generateOperations();
		$model=new Authitem;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Authitem']))
		{
               if($this->performSave()){
                        	$this->redirect(array('index'));
               }
		}

		$this->render('create',array(
			'model'=>$model,			
		));

	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($name)
	{
		$this->generateOperations();
		$model=$this->loadModel($name);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Authitem']))
		{
			if($this->performSave($name))                        
                $this->redirect(array('index'));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($name)
	{
		if(Yii::app()->request->isPostRequest)
		{
			
			$transaction = Yii::app()->db->beginTransaction(); //memulai transaksi
	        try {
	        	$model = $this->loadModel($name);
	        	Authassignment::model()->deleteByItemname($model->name);
	        	Authitemchild::model()->deleteRows($model->name);
	        	// we only allow deletion via POST request
				$model->delete();	        	
	            $transaction->commit();
	        } catch (Exception $exc) {
	            $transaction->rollback();
	            throw  new CHttpException(400, $exc->getMessage());
	        }
	        
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
                $model=new Authitem('search');
                $model->unsetAttributes();  // clear any default values

		if(isset($_GET['Authitem']))
			$model->attributes=$_GET['Authitem'];

		$this->render('index',array(
			'model'=>$model,
		));
                
                /*
		$dataProvider=new CActiveDataProvider('Authitem');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
                */
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Authitem('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Authitem']))
			$model->attributes=$_GET['Authitem'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($name)
	{
        $model=Authitem::model()->find('name=\''.$name.'\'');
		if($model===null)
			throw new CHttpException(404,'Authitem=\''.$name.'\' does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='authitem-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	private function generateOperations(){
		$generator = $this->module->getGenerator();
        $items = $generator->getControllerActions();		
		$controllerKey='';
		$actionKey='';
		$result = array();
		foreach( $items['modules'] as $moduleName=>$moduleItems )
			if(strripos(strtolower($moduleName), 'user') === false && strripos(strtolower($moduleName), 'wewenang') === false){ //always exclude user & wewenang module ??
			foreach( $moduleItems['controllers'] as $key=>$item ){
				if (strripos(strtolower($item['name']), 'foto') === false && strripos(strtolower($item['name']), 'jenisberita') === false && strripos(strtolower($item['name']), 'page') === false && strripos(strtolower($item['name']), 'pagekategori') === false){
				$controllerKey = ucfirst($moduleName).'.'.$item['name'];
				if(strripos($item['name'], 'default') === false) //always exclude default controller
				foreach( $item['actions'] as $action ){
					if (strripos($action['name'], 'view') === false){
						$actionKey = $controllerKey.'.'.ucfirst($action['name']);	
						$result[]['name'] = $actionKey;
					}
				}
				}
				
			}
		}


		//find existing operations in DB and find the differences between existing modules
		$existingItems=Authitem::model()->findAllOperations();
		$result = $this->controllerDifferences($existingItems,$result);
		Authitem::model()->insertOperations($result); //insert new modules/controllers into DB		
	}
	public function actionCheckExistRole(){
		$allowed=true;
		$role='';
		$model=Authassignment::model()->find('userid=\''.$_POST['elmval'].'\'');
		if($model!==null) {
			$allowed=false;
			$role=$model->itemname;
		}

		echo json_encode(array('elmid'=>'#'.$_POST['elmid'],'allowed'=>$allowed,'role'=>$role));
	}
	private function controllerDifferences($queryResult,$generatorResult){
		$result = array();
		foreach($generatorResult as $generatorItem){
			$found=false;
			$controllerName='';
			foreach($queryResult as $queryItem){
				$contollerName = $generatorItem['name'];
				if($generatorItem['name'] === $queryItem['name']){
					$found=true;					
					break;
				}
			}
			if($found===false){
				$result[]['name'] = $contollerName;
			}
			if(empty($queryResult)){
				$result = $generatorResult;
			}
		}
		return $result;
	}
}
